package com.example.mq_sm.mqserver.datacenter;

import com.example.mq_sm.common.MQException;
import com.example.mq_sm.mqserver.core.Binding;
import com.example.mq_sm.mqserver.core.Exchange;
import com.example.mq_sm.mqserver.core.MSGQueue;
import com.example.mq_sm.mqserver.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * 对消息文件和数据库文件的同一封装，对于在硬盘上数据的调用只需要使用这一个类即可
 */
public class DiskDataCenter {
    DataBaseManager dataBaseManager = new DataBaseManager();
    MessageFileManager messageFileManager = new MessageFileManager();

    public void init(){
        dataBaseManager.init();
        messageFileManager.init();
    }

    // 先对数据库文件进行封装
    public void insertExchange(Exchange exchange){
        dataBaseManager.insertExchange(exchange);
    }

    public List<Exchange> selectAllExchanges(){
        return dataBaseManager.selectAllExchanges();
    }

    public void deleteExchange(String exchangeName){
        dataBaseManager.deleteExchange(exchangeName);
    }

    public void insertQueue(MSGQueue queue) throws IOException {
        dataBaseManager.insertQueue(queue);
        // 创建队列的同时, 不仅仅是把队列对象写到数据库中, 还需要创建出对应的目录和文件
        messageFileManager.createQueueFiles(queue.getName());
    }

    public List<MSGQueue> selectAllQueues(){
        return dataBaseManager.selectAllQueues();
    }

    public void deleteQueue(String queueName){
        dataBaseManager.deleteQueue(queueName);
    }

    public void insertBinding(Binding binding){
        dataBaseManager.insertBinding(binding);
    }

    public List<Binding> selectAllBindings(){
        return dataBaseManager.selectAllBindings();
    }

    public void deleteBinding(Binding binding){
        dataBaseManager.deleteBinding(binding);
    }

    // 下面是消息文件的封装
    public void createQueueFiles(String queueName) throws IOException {
        messageFileManager.createQueueFiles(queueName);
    }

    public void destroyQueueFiles(String queueName) throws IOException {
        messageFileManager.destroyQueueFiles(queueName);
    }

    public boolean checkFilesExist(String queueName){
        return messageFileManager.checkFilesExist(queueName);
    }

    public void sendMessage(MSGQueue queue, Message message) throws MQException, IOException {
        messageFileManager.sendMessage(queue, message);
    }

    public void deleteMessage(MSGQueue queue, Message message) throws IOException, ClassNotFoundException, MQException {
        messageFileManager.deleteMessage(queue, message);
        if (messageFileManager.checkGC(queue.getName())){
            messageFileManager.gc(queue);
        }
    }

    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws MQException, IOException, ClassNotFoundException {
        return messageFileManager.loadAllMessageFromQueue(queueName);
    }
}
























